package com.doge.calcalbum.business.home

import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.view.LayoutInflater
import android.view.WindowManager
import com.doge.calcalbum.R
import com.doge.calcalbum.api.model.WechatChannelInfo
import com.doge.calcalbum.databinding.DialogWechatPublicChannelBinding
import com.doge.calcalbum.utils.appContext
import com.doge.calcalbum.utils.dp
import com.doge.calcalbum.utils.load
import com.doge.calcalbum.utils.toast

class WechatPublicChannelDialog private constructor(context: Context, theme: Int) : Dialog(context, theme) {
    private class Params {
        lateinit var mContext: Context
        var canCancel = true
        lateinit var binding: DialogWechatPublicChannelBinding
        var channelInfo: WechatChannelInfo? = null
    }

    class Builder(context: Context) {
        private val p = Params()

        init {
            p.mContext = context
        }

        fun setChannel(channelInfo: WechatChannelInfo): Builder {
            p.channelInfo = channelInfo
            return this
        }

        fun show() {
            create().show()
        }

        fun create(): WechatPublicChannelDialog {
            val dialog = WechatPublicChannelDialog(
                p.mContext,
                R.style.Theme_Light_NoTitle_Dialog
            )
            dialog.window?.decorView?.setPadding(34.dp, 0, 34.dp, 0)
            val lp = dialog.window?.attributes
            lp?.width = WindowManager.LayoutParams.MATCH_PARENT
            lp?.height = WindowManager.LayoutParams.WRAP_CONTENT
            dialog.window?.attributes = lp

            p.binding = DialogWechatPublicChannelBinding.inflate(LayoutInflater.from(p.mContext))
            p.binding.imageQRCode.load(p.channelInfo?.imageQRCode)
            p.binding.name.text = p.channelInfo?.name

            p.binding.value.setOnClickListener {
                val manager = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
                val clipData = ClipData.newPlainText("wechatPublicChannel", p.channelInfo?.name)
                manager?.setPrimaryClip(clipData)
                toast(R.string.public_channel_copied)
            }

            dialog.setContentView(p.binding.root)
            dialog.setCanceledOnTouchOutside(p.canCancel)
            dialog.setCancelable(p.canCancel)
            return dialog
        }
    }
}